<?php
/**
 * Created by PhpStorm.
 * User: qingmu-523
 * Date: 2018/10/17
 * Time: 17:53
 */

namespace App\Command;


use Carbon\Carbon;
use PDO;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;

class CreateMsgAddressTmcCommand extends BaseCommand
{
    protected function configure()
    {
        $endTime = Carbon::now("Asia/Shanghai");
        $startTime = Carbon::now("Asia/Shanghai")->subMinute(10);
        $this
            ->setName('app:create-msg-address-tmc')
            ->setDescription('创建tmc订单的更改地址信息，更改地址')
            ->setHelp("创建tmc订单的更改地址信息")// configure an argument / 配置一个参数
            ->addOption("tid", '', InputOption::VALUE_OPTIONAL, "为该tid的订单生成更改地址tmc信息", 0)
            ->addOption("startTime", "", InputOption::VALUE_REQUIRED, "截取订单开始时间，默认查找前十分钟", $startTime)
            ->addOption("endTime", "", InputOption::VALUE_REQUIRED, "截取订单结束时间，默认查找前十分钟", $endTime);
    }

    /**
     * execute
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        date_default_timezone_set("Asia/Shanghai");
        $tid = $input->getOption('tid');
        $startTime = $input->getOption('startTime');
        $endTime = $input->getOption('endTime');
        $helper = $this->getHelper('question');
        $question = new ConfirmationQuestion('Whether to push directly into the redis queue?', false);

        $has_push_redis = false;
        if ($helper->ask($input, $output, $question)) {
            $has_push_redis = true;
        }
        $start_time = time();
        if ($tid != 0) {
            $info = $this->tmcdb->query("select * from jdp_tb_trade where tid = '$tid' ")->fetchAll(PDO::FETCH_ASSOC);
//            print_r($info);
            if (!$info){
                echo "检查jdp_tb_trade表是否存在tid:".$tid;
                exit;
            }
            $this->create_notify_address($info[0],$has_push_redis);
//            $return_data = $this->create_return($info[0]['tid'],$info[0]['oid'],$info[0]['seller_nick'],$info[0]['buyer_nick'],$has_good_return);
//            print_r($return_data);
        } else {
            for ($i = 0; ; $i++) {
                $sql = "select * from jdp_tb_trade  where jdp_created >= '$startTime' and jdp_created <='$endTime' limit ";
                $page_size = 100;
                $start = $i * $page_size;
                $infos = $this->tmcdb->query("$sql $start,$page_size")->fetchAll(PDO::FETCH_ASSOC);
                if (empty($infos)){
                    echo "查询结束\n\r";
                    exit(1);
                }
                foreach ($infos as $item) {
//                    $return_data = $this->create_return($item['tid'],$item,$item['seller_nick'],$item['buyer_nick'],$has_good_return);
                    $this->create_return($item,$has_push_redis);
                }
            }
        }
        $end_time = time();
        $output->writeln("结束时间：".$end_time);
        $output->writeln("耗时时间：".($end_time-$start_time));

        $output->writeln([
            'Order Creator',
            '============',
            '',
        ]);

        // outputs a message followed by a "\n"
        $output->writeln('Success!');


//        $process = new Process(array('figlet', 'Symfony'));
//
//        $helperprocess->run($output, $process);
//        sleep(2);
//        $progress = new ProgressBar($output);
////        $progress->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
//
//        // start and displays the progress bar
//        // 启动并显示进度条
//        $progress->start();
//        sleep(2);
//        $progress->advance();
//        $progress->finish();
    }

    /**
     * 插入队列
     * @param $item
     * @param $has_push_redis
     */
    public function add_queue($item,$has_push_redis)
    {
        if (!$has_push_redis) {
            return;
        }
        $item['topic'] = 'taobao_trade_TradeLogisticsAddressChanged';
        $item['nick'] = $item['seller_nick'];
        $item['time'] = microtime();
        $this->do_queue('taobaomsg', 'add', $item);
    }

    /**
     * 创建更改地址信息
     * @param $item
     * @param $has_push_redis
     */
    public function create_notify_address($item,$has_push_redis)
    {
        date_default_timezone_set("Asia/Shanghai");
        //从转单或推送单获取一笔天猫外部订单号
        $jdp_response = json_decode($item['jdp_response'],true);
        $tid = $item['tid'];
        $seller_nick = $item['seller_nick'];
        $buyer_nick = $item['buyer_nick'];
        $dt = date("Y-m-d H:i:s");
        $jdp_hashcode = time();

        $name = $buyer_nick;

        $jdp_response = $this->generatedMsgInfo($item);
        $creator = [
            "seller_nick" => $seller_nick,
            "buyer_nick" => $name,
            "created" => $dt,
            "tid" => $tid,
            "modified" => $dt,
            "jdp_hashcode" => $jdp_hashcode,
            "jdp_response" => $jdp_response,
            "jdp_created" => $dt,
            "jdp_modified" => $dt,

        ];
        // unset($responeJson);//用完及时销毁
        var_dump($this->tmcdb->update("jdp_tb_trade", $creator, array('tid'=>$tid)));
        $content = json_decode($jdp_response,true)['trade_fullinfo_get_response']['trade'];
        $channel_order_log_data = array(
            'channel_id' =>'',
            'tid' =>'',
            'type' =>1,
            'current_version' =>1,
            'content' => json_encode($content,JSON_UNESCAPED_UNICODE),
        );
        var_dump($this->omsdb->insert('t_channel_order_log',$channel_order_log_data));
        $this->add_queue($creator, $has_push_redis);
    }

    /**
     * 数据处理
     * @param $item
     * @return false|string
     */
    public function generatedMsgInfo($item)
    {
        $itemTmp = json_decode($item['jdp_response'],true);
        $address = array(
            "receiver_address"=> "新塘镇锦绣天伦花园二街",
            "receiver_city"=> "广州市",
            "receiver_district"=> "增城区",
            "receiver_mobile"=> "15914338482",
            "receiver_name"=> "杨景",
            "receiver_state"=> "广东省",
            "receiver_zip"=> "510900",
            "modified"=>date("Y-m-d H:i:s")
        );
        $itemTmp['trade_fullinfo_get_response']['trade'] = array_merge($itemTmp['trade_fullinfo_get_response']['trade'],$address);
        $responeJson = json_encode($itemTmp, JSON_UNESCAPED_UNICODE);
        return $responeJson;
    }


}
